const fastify = require("fastify")

const app = fastify({
    logger: true //日志开启
});

// decorate装饰器，可以给fastify添加自定义属性和方法
app.decorate("add", (a, b) => a + b);//添加到fastify上
app.decorateRequest("add", (a, b) => a + b)//添加到request上
app.decorateReply("add", (a, b) => a + b)//添加到reply上
// otps接收传递过来的参数
const myPlugin = (fastify, otps, done) => {
    // done == next
    const a = app.add(otps.num1, otps.num2)
    console.log(a);
    done()
}
// fastify中注册插件，类似于express中的中间件
app.register(myPlugin, { num1: 1, num2: 2 })

/*  console.log(request.query);//路径参数
 console.log(request.body);//body参数
 console.log(request.params);//路径动态参数 */


const getOptions = {
    schema: {
        // 请求类型限制
        querystring: {
            type: "object",
            properties: {
                name: { type: "string", default: "Jay", maxLength: 10 },
                age: { type: "number" }
            },
            required: ["age"]
        },
        // 响应类型定义上可增加吞吐率
        response: {
            200: {
                type: "object",
                properties: {
                    message: { type: "string" },
                    data: {
                        type: "array",
                        items: {
                            type: "object",
                            properties: {
                                name: { type: "string" },
                                age: { type: "number" }
                            }
                        }
                    }
                }
            }
        }
    },
    // 配置项
    config:{}
}
app.get("/get", getOptions, (request, reply) => {
    // reply.send不可通过return返回
    reply.send({ mesaage: "成功", data: [{ name: "Jay", age: 18 }, { name: "Jay", age: reply.add(1, 2) }] });
})

app.post("/", (request, reply) => {
    reply.send({ hello: "world" });
})

// 开启服务
app.listen({ port: 3000 }).then((address) => {
    console.log(`Server listening at ${address}`);
})